<template>
  <div class="">
    <!-- 弹窗 -->
    <el-dialog v-model="store.userInsertOpen" :show-close="false" append-to-body class="dialogClass" width="38%" draggable overflow >
      <!--弹窗标题-->
      <template #header="{ close, titleId }">
        <div class="dialogHeader">
          <span :id="titleId" class="dlgTitleClass" style="margin: 10px 10px;" v-if="store.updateUserId===0">新增</span>
          <span :id="titleId" class="dlgTitleClass" style="margin: 10px 10px; " v-if="store.updateUserId!==0">修改</span>
          <el-icon style="font-size: 18px;margin-top: 14px;cursor: pointer" @click="closeDialog">
            <CloseBold/>
          </el-icon>
        </div>
      </template>
      <!--弹窗内容-->
      <template #default>
        <el-form class="role-form" ref="addUserFormRef" :rules="rules" :model="addUserData" >
          <el-form-item label="登录名称" prop="loginName">
            <el-input v-model="addUserData.loginName" placeholder="请输入登录名称" :disabled="store.updateUserId!==0"></el-input>
          </el-form-item>
          <el-form-item label="用户姓名" prop="realName">
            <el-input v-model="addUserData.realName" placeholder="请输入用户姓名"></el-input>
          </el-form-item>
          <el-form-item label="身份证号" prop="idCard" >
            <el-input v-model="addUserData.idCard" placeholder="请输入身份证号"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="phone" >
            <el-input v-model="addUserData.phone" placeholder="请输入手机号码"></el-input>
          </el-form-item>
          <el-form-item label="电子邮箱" prop="email" >
            <el-input v-model="addUserData.email" placeholder="请输入电子邮箱"></el-input>
          </el-form-item>
          <el-form-item label="所属部门" prop="userDept" >
            <el-select v-model="addUserData.userDept" placeholder="请选择所属部门" >
              <el-option v-for="item in userDept"  :key="item.key" :value="item.key" :label="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="所属角色" prop="userDept" >
            <el-select v-model="addUserData.userRole" placeholder="请选择所属角色" >
              <el-option v-for="item in addRoleData"  :key="item.key" :value="item.key" :label="item.value"/>
            </el-select>
          </el-form-item>
          <el-row >
            <el-col :span="12">
              <el-form-item label="启用" label-width="78px" prop="status">
                <el-radio-group v-model="addUserData.status">
                  <el-radio border :label="0">是</el-radio>
                  <el-radio border :label="1">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="类型" label-width="78px" prop="status">
                <el-radio-group v-model="addUserData.userType">
                  <el-radio border :label="1">老师</el-radio>
                  <el-radio border :label="2">学生</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="性别" label-width="78px" prop="status">
            <el-radio-group v-model="addUserData.sex">
              <el-radio border :label="0">男</el-radio>
              <el-radio border :label="1">女</el-radio>
            </el-radio-group>
          </el-form-item>

        </el-form>
      </template>
      <!--弹窗底部-->
      <template #footer>
        <span class="myDialogFooter">
          <el-button class="el-button__default" @click="closeDialog">取 消</el-button>
          <el-button type="primary" class="el-button__primary" @click="addUserInfo()" v-if="store.updateUserId===0">确认添加</el-button>
          <el-button type="primary" class="el-button__primary" @click="updateRoleInfo()" v-if="store.updateUserId!==0">确认修改</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {defineEmits, onMounted, reactive, ref, watch} from "vue";
import {CloseBold} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {userStore} from "@/stores/user/userStore.js";
import {addOrUpdateRole, getRoleInfoById, getRoles} from "@/api/role/index.js";
import {getDeptList} from "@/api/dept/index.js";
import {addOrUpdateUser, getUserInfoById} from "@/api/user/index.js";
const addUserFormRef = ref()
const emit = defineEmits(['refresh'])
const userDept=ref([])
const addUserData=ref({
  id:null,
  userDept:null,
  status:0,
  sex:0,
  userType:2,
  loginName:"",
  realName:"",
  phone:"",
  email:"",
  idCard:"",
  userRole:""
})
const addRoleData= ref([])
const store=userStore()
const rules = reactive({
  userDept: [
    { required: true, message: "用户部门不能为空", trigger: "blur" }
  ],
  status: [
    { required: true, message: "状态不能为空", trigger: "blur" }
  ],
  sex: [
    { required: true, message: "性别不能为空", trigger: "blur" }
  ],
  userType: [
    { required: true, message: "用户类型不能为空", trigger: "blur" }
  ],
  loginName: [
    { required: true, message: "登录名不能为空", trigger: "blur" }
  ],
  realName: [
    { required: true, message: "真实姓名不能为空", trigger: "blur" }
  ],
  phone: [
    { required: true, message: "手机号码不能为空", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
  ],
  email: [
    { required: true, message: "邮箱不能为空", trigger: "blur" },
    { pattern: /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/, message: "请输入正确的邮箱地址", trigger: "blur" }
  ],
  idCard: [
    { required: true, message: "身份证号码不能为空", trigger: "blur" },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: "请输入正确的身份证号码", trigger: "blur" }
  ]
});

onMounted(()=>{
  initUserDept()
  initRoleInfo()
})
//观察menuId变化

watch(store,()=>{
  if (store.updateUserId!==0){
    console.log(store.updateUserId)
    initUserInfo(store.updateUserId)
  }
})

/**
 * 获取
 * @param id
 * @returns {Promise<void>}
 */
const initRoleInfo=async () => {
  const res = await getRoles()
  addRoleData.value=res.data
}

const initUserDept=async () => {
  const res = await getDeptList()
  userDept.value=res.data
}
const initUserInfo=async (id)=>{
  const res=await getUserInfoById(id)
  addUserData.value=res.data
}

const addUserInfo = async () => {
 const valid= await addUserFormRef.value.validate()
 if(valid) {
   try {
     const res = await addOrUpdateUser(addUserData.value,"add")
     ElMessage.success("添加成功")
     await closeDialog()
     emit('refresh')
   }catch (e){}
 }
}
const updateRoleInfo =async () => {
  console.log(addRoleData.value)
  const valid= await addUserFormRef.value.validate()
  if(valid) {
    ElMessageBox.confirm(
        '此操作将永久修改该角色, 是否继续?',
        '提示', {
          app: undefined, components: undefined, config: undefined, directives: undefined, mixins: [], provides: undefined,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    ).then(async () => {
      const res =await addOrUpdateUser(addUserData.value,"edit")
      if (res.code === 200) {
        ElMessage.success("修改成功")
        await closeDialog()

      }
    }).catch(() => {
    })
  }
}
const  closeDialog = () => {
  store.setUserInsertOpen(false)
  addUserFormRef.value.resetFields()
  addUserData.value={
    id:null,
    userDept:null,
    status:0,
    sex:0,
    userType:2,
    loginName:"",
    realName:"",
    phone:"",
    email:"",
    idCard:"",
    userRole:""
  }
  emit('refresh')
}
</script>

<style scoped>
.dialogClass .dlgTitleClass {
}

.el-dialog .el-dialog__header {
  margin: 0 !important;
  padding: 0 !important;
}

.el-dialog .dialogHeader {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  height: 40px;
  margin: 0 10px;
  font-size: 18px;
  font-weight: bolder;
}

/* 确保对话框主体可以使用flex布局 */
:deep(.el-dialog__body) {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  padding: 0 50px!important;
}

.role-form {
  margin:0  50px; /* 自动边距用于水平居中 */
}

.el-dialog .el-dialog__footer {
  padding: 10px;
}

/* 统一选择框、数字框和输入框的宽度 */
.el-input,
.el-input-number,
.el-select,
.el-tree-select{
  --el-select-input-focus-border-color: rgb(46, 92, 246);
  --el-color-primary: rgb(46, 92, 246);
  width: 100%; /* 或者设置一个具体的像素值，比如240px */
  box-sizing: border-box; /* 确保内边距和边框包含在元素的总宽度和高度内 */
}

.el-radio.is-bordered.is-checked {
  --el-color-primary: rgb(46, 92, 246);
}

.el-radio {
  --el-radio-input-border-color-hover: rgb(46, 92, 246);
}
</style>